<template>
    <Row>
        <Col span="22" offset="1">
            <Form ref="Company" :model="Company" :rules="ruleValidate" :label-width="150" :style="{marginTop: '30px'}">
                <Row>
                    <Col span="10" offset="2">
                        <FormItem label="公司编码">
                            <Input v-model.trim="Company.NumCode" readonly placeholder="公司编码由系统自动生成" ></Input>
                        </FormItem>
                    </Col>
                </Row>
                <Divider orientation="left">公司基本信息</Divider>
                <Row>
                    <Col span="10" offset="2">
                        <FormItem label="统一社会信用代码" prop="SocialCreditCode">
                            <Input  v-model.trim="Company.SocialCreditCode" placeholder="例如：91330681077558686H" >
                                <Button slot="append" @click="QueryCompaynFromQCC" icon="ios-search"></Button>
                            </Input>
                        </FormItem>
                    </Col>
                    <Col span="10">
                        <FormItem label="组织机构代码" prop="OrgnizationCode">
                            <Input  v-model.trim="Company.OrgnizationCode" readonly placeholder="07755868-6" ></Input>
                        </FormItem>
                    </Col>
                    <Col span="20" offset="2">
                        <FormItem label="公司名称" prop="Name">
                            <Input  v-model.trim="Company.Name" placeholder="例如：浙江祥生建设工程有限公司" ></Input>
                        </FormItem>
                    </Col>
                    <Col span="10" offset="2">
                        <FormItem label="公司简称" prop="NickName">
                            <Input v-model.trim="Company.NickName" placeholder="例如：祥生建设" ></Input>
                        </FormItem>
                    </Col>
                    <Col span="10" >
                        <FormItem label="法定代表人" prop="LegalRepresentative">
                            <Input v-model.trim="Company.LegalRepresentative" placeholder="例如：XXX" ></Input>
                        </FormItem>
                    </Col>
                    <Col span="10" offset="2">
                        <FormItem label="注册资本" prop="Capital">
                            <Input 
                                prefix="logo-yen" 
                                style="width:100%"
                                v-model.number="Company.Capital" 
                                placeholder="例如：50000000.00" >
                            </Input>
                        </FormItem>
                    </Col>
                    <Col span="10" >
                        <FormItem label="公司类别" prop="CompanyType">
                            <!-- <Input v-model.trim="Company.ItemType" placeholder="例如：土建、消防、涂料、其他" ></Input> -->
                            <Select v-model.trim="Company.CompanyType" filterable >
                                <Option v-for="item in CompanyTypes" :value=item.value :key="item.value">{{ item.label }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                </Row>
                
                <Divider orientation="left">公司地址信息</Divider>
                <Row>
                    <Col span="10" offset="2">
                        <FormItem label="省份" prop="Province">
                            <!-- <Input v-model.trim="Company.Province" placeholder="例如：浙江省、湖南省、上海市" ></Input> -->
                            <Select v-model.trim="Company.Province" :loading="ProvinceStatus" :remote-method="SelectProvince" @on-open-change="ProvinceChanged" filterable clearable placeholder="请选择省份">
                                <Option v-for="item in Province" :value=item.value :key="item.Id">{{ item.label }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="10" >
                        <FormItem label="城市" prop="City">
                            <!-- <Input v-model.trim="Company.City" placeholder="例如：绍兴市、杭州市、宁波市" ></Input> -->
                            <Select v-model.trim="Company.City" :loading="CityStatus" :remote-method="SelectCity" @on-open-change="CityChanged" filterable clearable placeholder="请选择城市">
                                <Option v-for="item in City" :value=item.value :key="item.Id">{{ item.label }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span="10" offset="2">
                        <FormItem label="市（县）、区"  prop="Zone">
                            <!-- <Input v-model.trim="Company.Zone" placeholder="例如：诸暨市、丽水市、绍兴县" ></Input> -->
                            <Select v-model.trim="Company.Zone" :loading="ZoneStatus" :remote-method="SelectZone" @on-open-change="ZoneChanged" filterable clearable placeholder="请选择市（县）、区">
                                <Option v-for="item in Zone" :value=item.value :key="item.Id">{{ item.label }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span="20" offset="2">
                        <FormItem label="详细地址" prop="AddressDetail">
                            <Input  v-model.trim="Company.AddressDetail" placeholder="例如：XXX街道，XXX路,XXX号" ></Input>
                            <!-- <Button slot="append" @click="modal1 = true" icon="ios-search"></Button> -->
                        </FormItem>
                    </Col>
                </Row>
                <Divider orientation="left">营业执照信息</Divider>
                <Row>
                    <Col span="10" offset="2">
                        <FormItem label="注册时间" prop="RegistTime">
                            <DatePicker v-model="Company.RegistTime" type="date" placeholder="请选择日期" format="yyyy年MM月dd日" style="width:100%"></DatePicker>
                        </FormItem>
                    </Col>
                    <Col span="10">
                        <FormItem label="成立日期" prop="EstablishTime">
                            <DatePicker v-model="Company.EstablishTime" type="date" placeholder="请选择日期" format="yyyy年MM月dd日" style="width:100%"></DatePicker>
                        </FormItem>
                    </Col>
                    <!--  <Col span="10" offset="2">
                        <FormItem label="营业期限" prop="AllowBeginTime">
                            <DatePicker type="daterange" :options="BuseinessTimeoptions" format="yyyy年MM月dd日" placement="bottom-end" placeholder="10年、20年、30年、长期" style="width:100%"></DatePicker>
                        </FormItem>
                    </Col>
                    <Col span="10" >
                        <FormItem label="经营时长">
                            <Input v-model.trim="BusinessDuringTime" disabled placeholder="例如：10年、20年、长期" ></Input>
                        </FormItem>
                    </Col> -->
                    <Col span="10" offset="2">
                        <FormItem label="开业时间" prop="AllowBeginTime">
                            <DatePicker v-model="Company.AllowBeginTime" type="date" placeholder="请选择日期" format="yyyy年MM月dd日" style="width:100%"></DatePicker>
                        </FormItem>
                    </Col>
                    <Col span="10">
                        <FormItem label="闭业时间" prop="AllowEndTime">
                            <DatePicker v-model="Company.AllowEndTime" type="date" placeholder="请选择日期" format="yyyy年MM月dd日" style="width:100%"></DatePicker>
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span="20" offset="2">
                        <FormItem label="经营范围" prop="Business">
                            <Input v-model="Company.Business" type="textarea" :autosize="{minRows: 5,maxRows: 10}" placeholder="请输入经营范围，营业执照上的经营范围" />
                        </FormItem>
                    </Col>
                </Row>
                <Divider orientation="left">其他信息</Divider>
                <Row>
                    <Col span="10" offset="2">
                        <FormItem label="公司状态">
                            <Select v-model.number="Company.Status" >
                                <Option v-for="item in Status" :value=item.value :key="item.label">{{ item.label }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="10" >
                        <FormItem label="创建时间">
                            <DatePicker v-model="Company.CreateTime" type="date" placeholder="请选择日期" format="yyyy年MM月dd日 HH时mm分ss秒" readonly style="width:100%"></DatePicker>
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span="20" offset="2" style="text-align:center;margin-top:58px">
                        <Button type="primary" @click="Submit('Company')">提交</Button>
                        <Button @click="Reset('Company')" style="margin-left: 108px">重置</Button>
                    </Col>
                </Row>
            </Form>
        </Col>
    </Row>
</template>
<script>
import { mapState } from "vuex";
import { CreateCode,GetOne,Create,Update } from '@/axios/api/CompanyAPI'
import { GetProvinceList,GetCityList,GetZoneList } from '@/axios/api/AdministrativeAPI'

export default {
    computed:{
        ...mapState('company',[
            'currentCompanyID',
            'pageIndex',
            'pageSize',
        ])
    },
    components: {
        
    },
    mounted: function(){
        //console.log(this.currentCompanyID)

        if(this.currentCompanyID != ''){
            this.$Spin.show();
        }
        setTimeout(() => {
            this.$Spin.hide();
        }, 1000);

        if(this.currentCompanyID != ''){
            GetOne(this.currentCompanyID).then(res => {
                this.Company.Id = res.Id;
                this.Company.Num = res.Num;
                this.Company.NumCode = res.NumCode;
                this.Company.SocialCreditCode = res.SocialCreditCode;
                this.Company.OrgnizationCode = res.SocialCreditCode.slice(7,-2) + '-' + res.SocialCreditCode.slice(-2,-1);
                this.Company.Name = res.Name;
                this.Company.NickName = res.NickName;
                this.Company.LegalRepresentative = res.LegalRepresentative;
                this.Company.Capital = res.Capital;
                this.Company.CompanyType = res.CompanyType;
                this.Company.Province = res.Province;
                this.Company.City = res.City;
                this.Company.Zone = res.Zone;
                this.Company.AddressDetail = res.AddressDetail;
                this.Company.RegistTime = res.RegistTime;
                this.Company.EstablishTime = res.EstablishTime;
                this.Company.AllowBeginTime = res.AllowBeginTime;
                this.Company.AllowEndTime = res.AllowEndTime;
                this.Company.Business = res.Business;
                this.Company.Status = res.Status;
                this.Company.CreateTime = res.CreateTime;
            });
        }
        else{
            CreateCode().then(res => {
                this.Company.NumCode = res.toString();
            })
        }

        //加载省、市、县
        setTimeout(() => {
            GetProvinceList().then(res => {
                const list = res.map(item => {
                    return {
                        value: item.Code,
                        label: item.Name,
                        Id: item.Id
                    };
                });
                this.Province = list;

            setTimeout(() => {
                GetCityList(this.Company.Province).then(res => {
                    const list = res.map(item => {
                        return {
                            value: item.Code,
                            label: item.Name,
                            Id: item.Id
                        };
                    });
                    this.City = list;

                    setTimeout(() => {
                        GetZoneList(this.Company.City).then(res => {
                                const list = res.map(item => {
                                    return {
                                        value: item.Code,
                                        label: item.Name,
                                        Id: item.Id
                                    };
                                });
                                this.Zone = list;
                            })
                        }, 50);
                    })
                }, 50);
            })
        }, 50);
    },
    data () {
        return {
            Company: {
                Id: '00000000-0000-0000-0000-000000000000',
                Num: 1,
                NumCode: '',
                SocialCreditCode: '',
                OrgnizationCode: '',
                Name: '',
                NickName: '',
                Capital: 0.0,
                CompanyType: "4",
                LegalRepresentative: '',
                Province: '',
                City: '',
                Zone: '',
                AddressDetail: '',
                RegistTime: new Date(),
                EstablishTime: new Date(),
                AllowBeginTime: new Date(),
                AllowEndTime: new Date(),
                Business: '',
                Status: 0 ,
                CreateTime: new Date()
            },
            ruleValidate: {
                Num: [{ type: 'number', message: '只能输入数字', trigger: 'blur' }],
                Province: [{ required: true, message: '公司所在省份为必填！', trigger: 'blur'  }],
                City: [{ required: true, message: '公司所在地级市为必填！', trigger: 'blur'  }],
                Zone: [{ required: true, message: '公司所在县级市为必填！', trigger: 'blur'  }],
                SocialCreditCode: [{ required: true, message: '统一社会信用代码为必填项！', trigger: 'blur'  }],
                LegalRepresentative: [{ required: true, message: '法人代表为必填项！', trigger: 'blur'  }],
                AddressDetail: [{ required: true, message: '详细地址为必填项！', trigger: 'blur'  }],
                Business: [{ required: true, message: '营业范围为必填项！', trigger: 'blur'  }],
                Name: [{ required: true, message: '公司名称为必填项！', trigger: 'blur'  }],
                Capital: [{ required: true,type: 'number', message: '注册资本只能输入数字', trigger: 'blur' }]
            },
            Status:[
                {
                    value: 0,
                    label: "正常"
                },
                {
                    value: 1,
                    label: "预注销"
                },
                {
                    value: 3,
                    label: "注销中"
                },
                {
                    value: 4,
                    label: "已注销"
                }
            ],
            CompanyTypes: [
                {
                    value: "0",
                    label: "母公司"
                },
                {
                    value: "1",
                    label: "子公司"
                },
                {
                    value: "3",
                    label: "分公司"
                },
                {
                    value: "4",
                    label: "公司"
                }
            ],
            callmodal: "company-sheet",
            Province:[],
            City:[],
            Zone:[],
            ProvinceStatus: false,
            CityStatus: false,
            ZoneStatus: false,
            BusinessDuringTime: '',
            BuseinessTimeoptions: {
                    shortcuts: [
                        {
                            text: '10年',
                            value () {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                                return [start, end];
                            }
                        },
                        {
                            text: '20年',
                            value () {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                                return [start, end];
                            }
                        },
                        {
                            text: '30年',
                            value () {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                                return [start, end];
                            }
                        },
                        {
                            text: '长期',
                            value () {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                                return [start, end];
                            }
                        }
                    ]
                }
        }
    },
    watch: {
        'Company.SocialCreditCode'(value){
            if(value != '' && value != null && value.length == 18){
                this.Company.OrgnizationCode = value.toString().substring(7,value.length-2) + '-' + value.toString().slice(-2,-1);
            }
        }
    },
    methods: {
        Submit (name){
            //this.$Message.success('按了OK键');
             this.$refs[name].validate((valid) => {
                if (valid) {
                    if(this.Company.Id == '00000000-0000-0000-0000-000000000000'){
                        this.$Message.success('校验通过!');
                        Create(this.Company).then(res => {
                            if(res > 0){

                                setTimeout(() => {
                                    this.$store.dispatch('company/UpdateTableAsync',{
                                        PageIndex: this.pageIndex,
                                        PageSize: this.pageSize
                                    });

                                        this.$Notice.success({
                                        title: '操作提示',
                                        desc: '保存成功！ '
                                    });
                                }, 1000)
                                
                            }
                            else{
                                this.$Notice.error({
                                    title: '操作提示',
                                    desc: '保存失败！ '
                                });
                            }
                        }).catch(err =>{
                            this.$Notice.error({
                                title: '操作提示',
                                desc: '保存失败：' + err.data + '!'
                            });
                        })
                        
                    }
                    else{
                        this.$Message.success('校验通过!');
                        
                        Update(this.Company).then(res => {
                            if(res > 0){
                                setTimeout(() => {
                                    this.$store.dispatch('company/UpdateTableAsync',{
                                        PageIndex: this.pageIndex,
                                        PageSize: this.pageSize
                                    });

                                        this.$Notice.success({
                                        title: '操作提示',
                                        desc: '更新成功！'
                                    });
                                }, 1000)
                            }
                            else{
                                this.$Notice.success({
                                    title: '操作提示',
                                    desc: '更新失败！'
                                });
                            }
                        }).catch(err =>{
                            this.$Notice.error({
                                title: '操作提示',
                                desc: '更新失败：' + err.data + '!'
                            });
                        })
                    }
                    this.ChangeModal();
                } else {
                    this.$Message.error('校验失败!');
                    //this.ChangeModal('Company');
                }
            })
            
        },
        Reset (name){
            console.log(this.$refs[name]);
            this.$refs[name].resetFields();
        },
        ChangeModal (){
            //this.$refs[name].resetFields();
            this.$store.commit('company/CHANGE_MODAL');
            this.$router.push('/hr/Company')
        },
        SelectProvince (query){
            if(query != ''){
                this.ProvinceStatus = true;
                setTimeout(() => {
                    this.ProvinceStatus = false;
                    GetProvinceList().then(res => {
                        const list = res.map(item => {
                            return {
                                value: item.Code,
                                label: item.Name,
                                Id: item.Id
                            };
                        });
                        this.Province = list.filter(item => item.label.indexOf(query) > -1);
                    })
                }, 200);
            }
        },
        ProvinceChanged(IsOpen){
            if(IsOpen){
                GetProvinceList().then(res => {
                    const list = res.map(item => {
                        return {
                            value: item.Code,
                            label: item.Name,
                            Id: item.Id
                        };
                    });
                    this.Province = list;
                })
                this.Company.City = '';
                this.Company.Zone = '';
            }
            
        },
        SelectCity (query){
            if(query !== ''){
                this.CityStatus = true;
                setTimeout(() => {
                    this.CityStatus = false;
                    GetCityList(this.Company.Province).then(res => {
                        const list = res.map(item => {
                            return {
                                value: item.Code,
                                label: item.Name,
                                Id: item.Id
                            };
                        });
                        this.City = list.filter(item => item.label.indexOf(query) > -1);
                    })
                }, 200);
            }
        },
        CityChanged(IsOpen){
            if(IsOpen){
                GetCityList(this.Company.Province).then(res => {
                    const list = res.map(item => {
                        return {
                            value: item.Code,
                            label: item.Name,
                            Id: item.Id
                        };
                    });
                    this.City = list;
                })
                this.Company.Zone = '';
            }
        },
        SelectZone (query){
            if(query !== ''){
                this.ZoneStatus = true;
                setTimeout(() => {
                    this.ZoneStatus = false;
                    GetZoneList(this.Company.City).then(res => {
                        const list = res.map(item => {
                            return {
                                value: item.Code,
                                label: item.Name,
                                Id: item.Id
                            };
                        });
                        this.Zone = list.filter(item => item.label.indexOf(query) > -1);
                    })
                }, 200);
            }
        },
        ZoneChanged(){
            GetZoneList(this.Company.City).then(res => {
                const list = res.map(item => {
                    return {
                        value: item.Code,
                        label: item.Name,
                        Id: item.Id
                    };
                });
                this.Zone = list;
            })
        },
        QueryCompaynFromQCC(){
            alert('暂未实现企查查接口！');
        }
    }
}
</script>
